set seed 21112023

***THIS CODE WILL GENERATE BOOTSTRAP SAMPLES, WHICH WE SAVE, THEN ESTIMATE IN A LATER DO FILE
**ALLOWS US TO RUN ESTIMATION ON MULTIPLE COMPUTERS (WHILE FIXING SEED)
local bsamplesize = 100

**************Decomposition Sample

use "$working/Demand_TFPQIV_Qkl_sampleFS", clear
merge 1:1 co_code1 year using "$working/ProdQ_new_kl_sampleSS"

generate mid_s = 1 if _merge==3 // D and SS
replace mid_s = 2 if _merge==1 // D only
replace mid_s = 3 if _merge==2 // SS only

drop _merge

merge  1:1 co_code1 year using "$working/ProdQ_new_kl_sampleFS"

generate samples = 1 if _merge==3 & mid_s ==1 // D, FS, SS
replace samples = 2 if _merge==3 & mid_s==2 // D and FS
replace samples = 3 if _merge==3 & mid_s==3 // SS and FS

replace samples = 4 if _merge==1 & mid_s==1 // D and SS only
replace samples  = 5 if _merge==1 & mid_s==2 // D only
replace samples  = 6 if _merge==1 & mid_s==3 // SS and FS

replace samples = 7 if _merge==2 // FS only

tabulate samples

**Samples 2 is too rare: put into 1 
replace samples = 1 if samples==2
drop _merge
drop mid_s

sum
**grab the products that are just in FS
preserve
	merge 1:m co_code1 year using "$working/ProdQ_new_kl_sampleFS_prod"
	keep if _merge==3 & samples==3 | samples==7
	drop _merge
	tempfile t1
	save `t1', replace
restore

merge 1:m co_code1 year using "$working/Demand_TFPQIV_Qkl_sampleFS_prod"
drop if _merge==1 // These are products that are only in FS, not demand
drop _merge
append using `t1'

preserve

	collapse (mean) samples, by(co_code1 year)

	sum

restore
	
save "$working/sample_ProdQ_kl_TFPQIV", replace

forvalues bs = 1(1)`bsamplesize' {
	clear
	***Grab bootstrap samples
	use "$working/sample_ProdQ_kl_TFPQIV"
	bsample,  strata(samples) cluster(co_code1) idcluster(bs_co_code1)
	save "$BS_fold_old/record/Qkl/bssample_`bs'", replace
}
